/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.resource.web;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.utils.JsonModel;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.resource.entity.ResourceCtfSet;
import com.lczyfz.istep.modules.resource.entity.ResourceCtfSetSubject;
import com.lczyfz.istep.modules.resource.entity.ResourceCtfSubject;
import com.lczyfz.istep.modules.resource.service.ResourceCtfSetService;
import com.lczyfz.istep.modules.resource.service.ResourceCtfSetSubjectService;
import com.lczyfz.istep.modules.resource.service.ResourceCtfSubjectService;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * CTF题目集管理Controller
 * @author dh
 * @version 2017-01-16
 */
@Controller
@RequestMapping(value = "${adminPath}/resource/resourceCtfSet")
public class ResourceCtfSetController extends BaseController {

	@Autowired
	private ResourceCtfSetService resourceCtfSetService;

	@Autowired
	private ResourceCtfSubjectService resourceCtfSubjectService;

	@Autowired
	private ResourceCtfSetSubjectService resourceCtfSetSubjectService;

	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public ResourceCtfSet get(@RequestParam(required=false) String id) {
		ResourceCtfSet entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = resourceCtfSetService.get(id);
		}
		if (entity == null){
			entity = new ResourceCtfSet();
		}
		return entity;
	}
	
	@RequiresPermissions("resource:resourceCtfSet:view")
	@RequestMapping(value = {"list", ""})
	public String list(ResourceCtfSet resourceCtfSet, HttpServletRequest request, HttpServletResponse response, Model model) {

		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");

		}
		else
		{
			model.addAttribute("isSuperAdmin", "false");
		}
		Page<ResourceCtfSet> page = resourceCtfSetService.findPage(new Page<ResourceCtfSet>(request, response), resourceCtfSet);
		model.addAttribute("page", page);
		return "modules/resource/resourceCtfSetList";
	}

	@RequiresPermissions("resource:resourceCtfSet:view")
	@RequestMapping(value = "form")
	public String form(ResourceCtfSet resourceCtfSet, Model model,String type) {
		logger.debug("resourceCourse=== [{}]",resourceCtfSet);
		logger.debug("resourceCourse===111 [{}]",resourceCtfSet.getId());

		ResourceCtfSubject resourceCtfSubject = new ResourceCtfSubject();
		List<ResourceCtfSubject> resourceCtfSubjectList = resourceCtfSubjectService.findList(resourceCtfSubject);
		int count=0;
		if(resourceCtfSet!=null&&resourceCtfSet.getId()!=null&&!resourceCtfSet.getId().equals(""))
		{
//			logger.debug("课程id [{}]", resourceCourse.getId());
			ResourceCtfSetSubject resourceCtfSetSubject = new ResourceCtfSetSubject();
			resourceCtfSetSubject.setCtfSetId(resourceCtfSet.getId());
			logger.debug("CtfSetId=== [{}]", resourceCtfSetSubject.getCtfSetId());
//			resourcePaperQuestion.setPaperId(resourcePaper.getId());
			List<ResourceCtfSetSubject> resourceCtfSetSubjectList=resourceCtfSetSubjectService.findList(resourceCtfSetSubject);

			for (int i = 0; i < resourceCtfSubjectList.size(); i++) {
				if(resourceCtfSetSubjectList.size()==0)
				{
					break;
				}else {
//		fd

					for (int j = 0; j < resourceCtfSetSubjectList.size(); j++) {
						if (resourceCtfSubjectList.get(i).getId().equals(resourceCtfSetSubjectList.get(j).getCtfSubjectId())) {

							resourceCtfSubjectList.get(i).setIsChoose("true");
							count++;
							resourceCtfSetSubjectList.remove(j);
							break;
						}else
							resourceCtfSubjectList.get(i).setIsChoose("false");


					}
				}
			}
		}
		if(type!=null&&type.equals("copy"))
		{

			resourceCtfSet.setCtfSetName(resourceCtfSet.getCtfSetName()+"-副本");
		}
		if (systemService.isSuperAdmin()) {
			model.addAttribute("isSuperAdmin", "true");
		} else
			model.addAttribute("isSuperAdmin", "false");

		model.addAttribute("resourceCtfSubjectList", resourceCtfSubjectList);
		model.addAttribute("type", type);
		model.addAttribute("resourceCtfSet", resourceCtfSet);

		return "modules/resource/resourceCtfSetForm";
	}

	@RequiresPermissions("resource:resourceCtfSet:edit")
	@RequestMapping(value = "save")
	public String save(ResourceCtfSet resourceCtfSet, Model model, RedirectAttributes redirectAttributes, String duallist,String type,String index) {
		if (!beanValidator(model, resourceCtfSet)){
			return form(resourceCtfSet, model,null);
		}
		if(type!=null&&type.equals("copy"))
		{
			logger.debug("复制CTF题目集！");
			ResourceCtfSet temp=resourceCtfSetService.findCtfSetByCtfSetName(resourceCtfSet);
			if (temp != null && temp.getCtfSetName().equals(resourceCtfSet.getCtfSetName())) {
				addMessage(redirectAttributes, "复制Ctf题目集'" + resourceCtfSet.getCtfSetName() + "'失败，该Ctf题目集已存在");
			}else {
				if (duallist == null || duallist.equals("")) {
					addMessage(redirectAttributes, "复制Ctf题目集失败，请选择需要的CTF题目");
				} else {
					ResourceCtfSet resourceCtfSet1=new ResourceCtfSet();

					resourceCtfSet1.setCtfSetName(resourceCtfSet.getCtfSetName());
					resourceCtfSet1.setCtfSetAttribute(resourceCtfSet.getCtfSetAttribute());
					resourceCtfSet1.setRemarks(resourceCtfSet.getRemarks());
//					resourceCtfSet1.setCtf(resourcePaper.getPaperType());
					resourceCtfSetService.save(resourceCtfSet1);
					resourceCtfSetSubjectService.save(duallist, resourceCtfSet1);
					addMessage(redirectAttributes, "复制CTF题目集'" + resourceCtfSet.getCtfSetName()+ "'成功");
				}
			}

		}else
		{
			if(resourceCtfSetService.get(resourceCtfSet)==null)
			{
				logger.debug("插入CTF题目集！");

				resourceCtfSet.setSubjectSum(String.valueOf(duallist.split(",").length));

				ResourceCtfSet temp = resourceCtfSetService.findCtfSetByCtfSetName(resourceCtfSet);
				if (temp != null && temp.getCtfSetName().equals(resourceCtfSet.getCtfSetName())) {
					addMessage(redirectAttributes, "添加题目集'" + resourceCtfSet.getCtfSetName() + "'失败，添加题目集已存在");
				}else {
					if (duallist == null || duallist.equals("")) {
						addMessage(redirectAttributes, "添加CTF题目集失败，请选择需要的CTF题目");
					} else {
							logger.debug("resourceCtfSet====", resourceCtfSet.getCtfSetName());
						resourceCtfSetService.save(resourceCtfSet);
//
//						logger.debug("课程id [{}]", resourceCourse.getId());
//						logger.debug("中间表服务 [{}]", resourceCoursewareCourseService);
						resourceCtfSetSubjectService.save(duallist, resourceCtfSet);
						addMessage(redirectAttributes, "添加CTF题目集'" + resourceCtfSet.getCtfSetName() + "'成功");
					}

				}
			}else{
				if (duallist == null || duallist.equals("")) {
					addMessage(redirectAttributes, "修改试卷失败，请选择需要的题目");
				} else {
					resourceCtfSet.setSubjectSum(String.valueOf(duallist.split(",").length));
					resourceCtfSetService.save(resourceCtfSet);
					resourceCtfSetSubjectService.update(duallist, resourceCtfSet);
					addMessage(redirectAttributes, "修改试卷'" + resourceCtfSet.getCtfSetName()+ "'成功");
				}

			}
		}
//		resourceCtfSetService.save(resourceCtfSet);
//		addMessage(redirectAttributes, "保存CTF题目集管理成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCtfSet/?repage";
	}

//	//ctf题目集属性联动获取ctf题目
//	@ResponseBody
//	@RequestMapping(value = "findCetSetListByAttribute")
//	public JsonModel findCetSetListByAttribute(@RequestParam(required = false) ResourceCtfSet resourceCtfSet) {
//		logger.debug("==Evan==trainProgramId:"+resourceCtfSet.getCtfSetAttribute());
//		JsonModel jsonModel = new JsonModel();
//		Map<String,List> map = new HashMap<>();
////		map.put("CourseSystemList",resourceCoursesystemService.findCourseSystemById(trainProgramId));
//		map.put("CtfSetList",resourceCtfSetService.findListByAttribute(resourceCtfSet));
////		map.put("PaperList",resourcePaperService.findPaperById(trainProgramId));
//		jsonModel.setDataObj(map);
//		return jsonModel;
//	}



	@RequiresPermissions("resource:resourceCtfSet:edit")
	@RequestMapping(value = "delete")
	public String delete(ResourceCtfSet resourceCtfSet, RedirectAttributes redirectAttributes) {
		resourceCtfSetService.delete(resourceCtfSet);
		addMessage(redirectAttributes, "删除CTF题目集管理成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCtfSet/?repage";
	}
	/**
	 * 根据培训方案id查询CTF题目集列表列表展示
	 * @param resourceCtfSet
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("resource:resourceCourseware:view")
	@RequestMapping(value = "findPageByTrainprogramId")
	public String findPageByTrainprogramId(ResourceCtfSet resourceCtfSet, HttpServletRequest request, HttpServletResponse response, Model model) {
		logger.debug("courseId=== [{}]", resourceCtfSet.getTrainprogramId());
		Page<ResourceCtfSet> page = resourceCtfSetService.findPageByTrainprogramId(new Page<ResourceCtfSet>(request, response), resourceCtfSet);
		logger.debug("page.getList().size()=== [{}]", page.getList().size());
		model.addAttribute("page", page);
		return "modules/resource/resourceCtfSetList";
	}

	//我的CTF-CTF题目集列表展示
	@RequestMapping(value = "stuCtfSetList")
	public String stuCtfSetList(ResourceCtfSet resourceCtfSet, HttpServletRequest request, HttpServletResponse response, Model model) {
		//ctfSetId是我的学习详情页里面的链接跳转
		String ctfSetId = request.getParameter("ctfSetId") ;
		logger.debug("==Evan==ctfSetId=="+ctfSetId);
		if(ctfSetId != null && !ctfSetId.equals("")){
			resourceCtfSet.setId(ctfSetId);
		}
		resourceCtfSet.setUserId(UserUtils.getUser().getId());
		Page<ResourceCtfSet> page = resourceCtfSetService.stuCtfSetList(new Page<ResourceCtfSet>(request, response), resourceCtfSet);
		model.addAttribute("page", page);
		return "modules/teach/stuCtfSetList";
	}
	@ResponseBody
	@RequestMapping(value = "findCtfSetListByAttribute")
	public JsonModel findCtfSetListByAttribute(@RequestParam(required = false) String attribute) {
		logger.debug("==dingh==" + attribute);
		JsonModel jsonModel = new JsonModel();
		ResourceCtfSubject resourceCtfSubject=new ResourceCtfSubject();
		resourceCtfSubject.setCtfSubjectAttribute(attribute);
		List<ResourceCtfSubject> resourceCtfSubjectList = resourceCtfSubjectService.findList(resourceCtfSubject);
		logger.debug("lsj" + resourceCtfSubjectList.size());
		jsonModel.setDataObj(resourceCtfSubjectList);
		return jsonModel;
	}
	@RequiresPermissions("resource:resourceCtfSet:view")
	@RequestMapping(value = "detail")
	public String detail(ResourceCtfSet resourceCtfSet, Model model, HttpServletRequest request, HttpServletResponse response) {

//		ResourceQuestion resourceQuestion=new ResourceQuestion();
//		resourceQuestion.setPaperId(resourcePaper.getId());
//
//		Page<ResourceQuestion> page = resourceQuestionService.findPageByPaperId(new Page<ResourceQuestion>(request, response), resourceQuestion);
//		model.addAttribute("page", page);
//		model.addAttribute("resourceQuestion", resourceQuestion);

		return "modules/resource/resourceCtfSetDetail";
	}

}